﻿#include "pch.h"
#include "hidinterfaceimpl.h"

HIDInterfaceImpl::HIDInterfaceImpl() {}

HIDInterfaceImpl::~HIDInterfaceImpl() {}

/* 打开 HID 设备 */
int HIDInterfaceImpl::open(unsigned short vendor_id, unsigned product_id) {
  int ret;

  ret = hid_init();
  if (ret == -1) {
    return ret;
  }

  hidDevice = hid_open(vendor_id, product_id, NULL);
  if (hidDevice == nullptr) {
    std::cout << "open hid api error: " << hid_error(NULL) << std::endl;
    hid_exit();
    return -1;
  }

  hid_set_nonblocking(hidDevice, 1);

  return 0;
}

/* 读取数据 */
int HIDInterfaceImpl::read(char *data, int length) {
  if (hidDevice != nullptr) {
    return hid_read(hidDevice, (unsigned char *)data, length);
  }
  return 0;
}

/* 写数据 */
int HIDInterfaceImpl::write(char *data, int length) {
  int ret = -1;
  if (hidDevice != nullptr) {
    ret = hid_write(hidDevice, (unsigned char *)data, length);
    if (ret == -1) {
      std::cout << "hid write err: " << hid_error(hidDevice) << std::endl;
    }
  } else {
    std::cout << "hidDevice is NULL..." << std::endl;
  }
  return ret;
}

/* 获取打开结果 */
int HIDInterfaceImpl::isOpen() { return hidDevice ? 1 : 0; }

/* 关闭 HID 设备*/
int HIDInterfaceImpl::close() {
  if (hidDevice != nullptr) {
    hid_close(hidDevice);
    this->hidDevice = nullptr;
  }

  hid_exit();
  return 0;
}
